/**
 * 
 */
package daos;

import java.util.List;

import hibernateUtils.HibernateUtil;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;



import exceptions.BadParametersException;
import exceptions.MediaExistsException;

import loansManagement.Loan;
import mediasManagement.Exemplary;
import mediasManagement.Media;



/**
 * @author virgil
 *
 */
public class MediaDAO {
	
	@SuppressWarnings("unchecked")
	public List<Media> findAll() {
		Session session = HibernateUtil.openSession();
		Query query = session.createQuery("from Media");
		List<Media> medias = query.list();
		return medias;
	}
	
	public List<Media> findAllByName(String mediaName) {
		Session session = HibernateUtil.openSession();
		Criteria criteria = session.createCriteria(Media.class).add(Restrictions.eq("title", mediaName));
		List<Media> medias = criteria.list();
		return medias;
	}

	public void addExemplary(Media media) throws MediaExistsException, BadParametersException{
		Session session = HibernateUtil.openSession();
		Media m=get(media.getMediaNumberId());
		m.addExemplary();
		session.merge(m);
	}
	public boolean add(Media media){

		Session session = HibernateUtil.openSession();
		//Add each exemplary
try{
	for(Exemplary ex: media.getExemplaries()){
		session.save(ex);
	}
			session.save(media);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	public boolean contains(Media media) throws MediaExistsException {
		Session session = HibernateUtil.openSession();
		if (media == null) throw new MediaExistsException();
		Media m = (Media) session.get(Media.class, media.getMediaNumberId());
		if (m ==null) return false;
		else return m.equals(media);	
	}
	public Media get(String mediaNumberId) throws MediaExistsException {
		Session session = HibernateUtil.openSession();
		Media m = (Media) session.get(Media.class, mediaNumberId);
		if (m ==null) throw new MediaExistsException();
		else return m;
	}
	//Get a exemplary
	public Exemplary getExamplary(String exemplaryId) throws MediaExistsException {
		Session session = HibernateUtil.openSession();
		Exemplary ex = (Exemplary) session.get(Exemplary.class, exemplaryId);
		if (ex ==null) throw new MediaExistsException();
		else return ex;
	}
	
}
